package com.quan.upms.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.quan.commons.base.BaseController;
import com.quan.commons.pojo.JSONResult;
import com.quan.commons.utils.PageBean;
import com.quan.upms.entity.UpmsUser;
import com.quan.upms.service.UpmsUserService;

@RestController
@RequestMapping(value = "/upms")
public class UpmsUserController extends BaseController {

	@Autowired
	private UpmsUserService service;

	@PostMapping(value = "/add")
	public Object add(@Valid @RequestBody UpmsUser entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return JSONResult.errorMsg(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		
		if (this.service.existValue(UpmsUser.class, "account", entity.getAccount()) > 0) {
			return JSONResult.errorMsg("账号已存在");
		}
		if (this.service.existValue(UpmsUser.class, "email", entity.getAccount()) > 0) {
			return JSONResult.errorMsg("邮件地址已存在");
		}
		if (this.service.existValue(UpmsUser.class, "mobile", entity.getAccount()) > 0) {
			return JSONResult.errorMsg("手机号码已存在");
		}
		
		entity.setId(Sid.nextShort());
		this.service.insertSelective(entity);
		return JSONResult.ok(entity.getId());
	}

	@PostMapping(value = "/delete")
	public Object delete(@RequestBody Map<String, Object> params) {
		String[] split = params.get("ids").toString().split(",");
		List<String> idsList = new ArrayList<String>();
		for (String id : split) {
			idsList.add("'" + id.trim() + "'");
		}
		return JSONResult.ok(StringUtils.join(idsList, ","));
	}

	@PostMapping(value = "/update")
	public Object update(@RequestBody UpmsUser entity) {
		this.service.updateSelective(entity);
		return JSONResult.ok();
	}

	@GetMapping(value = "/get/{id}")
	public Object get(@PathVariable String id) {
		return JSONResult.ok(this.service.selectOneById(id));
	}

	@PostMapping(value = "/list")
	public Object list(@RequestBody UpmsUser entity) {
		PageInfo<UpmsUser> pageInfo = this.service.selectPage(entity, new PageBean(request)) ;
		return JSONResult.ok(pageInfo);
	}

}
